package com.minelx.datamicroscope.core;

import com.minelx.woods.data.Task;
import com.minelx.woods.data.Tasks;

import java.util.Optional;

import static com.minelx.woods.data.TaskConstants.*;

public class JobRunner {

	private final Tasks tasks;

	private final NewTaskDealer taskDealer;

	public JobRunner(Tasks tasks, NewTaskDealer taskDealer) {
		this.tasks = tasks;
		this.taskDealer = taskDealer;
	}

	public void run() {
		Optional<Task> readyTask = tasks.anyReadyTask();
		if (!readyTask.isPresent()) {
			System.out.println("there is no ready task presented.");
			return;
		}
		System.out.println("start processing a task.");
		doATask(readyTask.get());
	}

	private void doATask(Task readyTask) {
		System.out.println("mark task as running.");
		// mark task as running
		readyTask.markAs(RUNNING);

		try {
			taskDealer.deal(readyTask);
			readyTask.markAs(DONE);
			System.out.println("file " + readyTask.values().getId() + " saved.");
		} catch (Exception e) {
			e.printStackTrace();
			// mark task as failed
			readyTask.markAs(FAILED);
		}
	}
}
